//
//  EJSHomeRecommendViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/21.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSHomeRecommendViewController.h"
#import "EJSHomeBannerView.h"
#import "EJSHorizontalGoodsCCell.h"
#import "EJSHomeRecommendHeaderReusableView.h"
#import "EJSFlashSaleHeaderReusableView.h"
#import "EJSFlashSaleFooterReusableView.h"
#import "EJSGoodsDetailInfoViewController.h"
#import "EJSGoodsListViewController.h"
#import "EJSGoodsListViewController.h"
#import "UIView+WhenTappedBlocks.h"

#import "EJSAdRequest.h"
#import "EJSRecommendRequest.h"
#import "EJSFlashSaleRequest.h"
#import "EJSCategoryModel.h"

@interface EJSHomeRecommendViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate>{
    NSTimer *_flashSaleTimer;
}

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) EJSHomeBannerView *bannerView;

@property (strong, nonatomic) NSMutableArray *recommendCategoryList;
@property (strong, nonatomic) NSMutableArray *recommendAdList;
@property (strong, nonatomic) NSMutableArray *flashSaleList;
@property (strong, nonatomic) EJSFlashSaleModel * currenFlashSale;

@end

@implementation EJSHomeRecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self getRecommendAdRequest];
    [self getFlashSaleList];
    [self getRecommendCategoryList];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configOwnViews
{
    [self configNavigationLeftItemWithImage:[UIImage imageNamed:@"gift_icon"]];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHorizontalGoodsCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell"];
    [self.collectionView registerClass:[EJSHomeRecommendHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSHomeRecommendHeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSFlashSaleHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSFlashSaleHeaderReusableView"];
     [self.collectionView registerNib:[UINib nibWithNibName:@"EJSFlashSaleFooterReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"EJSFlashSaleFooterReusableView"];
    
    self.bannerView = [[EJSHomeBannerView alloc] initWithFrame:CGRectMake(0, -k_EJSHomeBannerViewHeight, ScreenWidth, k_EJSHomeBannerViewHeight)];
    self.bannerView.cycleScrollView.delegate = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getRecommendAdRequest];
        [self getFlashSaleList];
        [self getRecommendCategoryList];
    }];
//    self.collectionView.mj_header.ignoredScrollViewContentInsetTop = 0;
   
    [self.collectionView addSubview:self.bannerView];
}

- (void)setRecommendAdList:(NSMutableArray *)recommendAdList{
    [self.collectionView.mj_header endRefreshing];
    if(_recommendAdList != recommendAdList){
        _recommendAdList = recommendAdList;
        NSMutableArray *adImageUrls = [NSMutableArray array];
        for (EJSAdModel *model in _recommendAdList) {
            [adImageUrls addObject:model.img?model.img:@""];
        }
        [self.bannerView.cycleScrollView setImageURLStringsGroup:adImageUrls];
        if(_recommendAdList.count > 0){
            [self.collectionView addSubview:self.bannerView];
            self.collectionView.contentInset = UIEdgeInsetsMake(k_EJSHomeBannerViewHeight, 0, 0, 0);
            self.collectionView.mj_header.ignoredScrollViewContentInsetTop = k_EJSHomeBannerViewHeight;
        }else{
            [self.bannerView removeFromSuperview];
            self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            self.collectionView.mj_header.ignoredScrollViewContentInsetTop = 0;
        }
    }
}
#pragma mark - 限时抢购
- (void)setCurrenFlashSale:(EJSFlashSaleModel *)currenFlashSale{
    [self.collectionView.mj_header endRefreshing];
    if(_currenFlashSale != currenFlashSale){
        _currenFlashSale = currenFlashSale;
        if(_flashSaleTimer){
            [_flashSaleTimer invalidate];
            _flashSaleTimer = nil;
        }
        if([self flashSaleUnderway]){
            _flashSaleTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(flashSaleTimerCountDown) userInfo:nil repeats:YES];
            [_flashSaleTimer fire];
        }
    }
    [self.collectionView reloadData];
}


- (BOOL)flashSaleUnderway{
    NSDate *flashStartDate = [self convertStringToDate:self.currenFlashSale.startTime];
    NSDate *flashEndDate = [self convertStringToDate:self.currenFlashSale.endTime];
    NSComparisonResult result = [[self localDate] compare:flashStartDate];
    NSComparisonResult result2 = [[self localDate] compare:flashEndDate];
    if((result == NSOrderedDescending || result == NSOrderedSame) && (result2 == NSOrderedAscending || result2 == NSOrderedSame)){
        return YES;
    }
    return NO;
}
- (NSDate *)localDate{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    return  [date  dateByAddingTimeInterval: interval];
}

- (NSDate *)convertStringToDate:(NSString *)string{
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];//时间管理
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *date = [formatter dateFromString:string];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    return  [date dateByAddingTimeInterval:interval];
}

- (void)flashSaleTimerCountDown{
    NSDate *flashSaleEndDate = [self convertStringToDate:self.currenFlashSale.endTime];
    NSDate *localDate = [self localDate];
    NSTimeInterval start = (NSInteger)[localDate timeIntervalSince1970]*1;
    NSTimeInterval end = (NSInteger)[flashSaleEndDate timeIntervalSince1970]*1;
    
    NSTimeInterval timeStamp = end - start;
    if(timeStamp > 0){
        int second = (int)timeStamp%60;//秒
        int minute = (int)timeStamp/60%60;
        int hour = (int)timeStamp/3600;
        NSString *hourString  = [NSString stringWithFormat:@"%02d",hour];
        NSString *minuteString  = [NSString stringWithFormat:@"%02d",minute];
        NSString *secondString  = [NSString stringWithFormat:@"%02d",second];
                
        EJSFlashSaleHeaderReusableView *flashSaleHeaderView = (EJSFlashSaleHeaderReusableView *)[self.collectionView supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
        if([flashSaleHeaderView isKindOfClass:[EJSFlashSaleHeaderReusableView class]] && flashSaleHeaderView.hTimeLabel && flashSaleHeaderView.mTimeLabel && flashSaleHeaderView.sTimeLabel){
            flashSaleHeaderView.timeCover.hidden = NO;
            flashSaleHeaderView.hTimeLabel.text = hourString;
            flashSaleHeaderView.mTimeLabel.text = minuteString;
            flashSaleHeaderView.sTimeLabel.text = secondString;
        }
    }else{
        [self.flashSaleList removeObject:self.currenFlashSale];
        if(self.flashSaleList.count > 0){
            self.currenFlashSale = self.flashSaleList.firstObject;
        }else{
            self.currenFlashSale = nil;
        }
    }
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    if(index < self.recommendAdList.count){
        EJSAdModel *model = _recommendAdList[index];
        if([model.linkType isEqualToString:@"goods"]){
            EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] initWithNibName:@"EJSGoodsDetailInfoViewController" bundle:nil];
            goodsDetailVC.goodsId = model.linkId;
            [self.navigationController pushViewController:goodsDetailVC animated:YES];
        }else if([model.linkType isEqualToString:@"category"]){
            EJSCategoryModel *categoryModel = [EJSCategoryModel new];
            categoryModel.categoryId = model.linkId;
            categoryModel.categoryName = model.adName;
            EJSGoodsListViewController *goodsListVC = [[EJSGoodsListViewController alloc] initWithNibName:@"EJSGoodsListViewController" bundle:nil];
            goodsListVC.categoryModel = categoryModel;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if(_currenFlashSale){
        return self.recommendCategoryList.count + 1;
    }
    return self.recommendCategoryList.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSHorizontalGoodsCCell *horizontalGoodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell" forIndexPath:indexPath];
    NSArray *goodsList = nil;
    if(_currenFlashSale){
        if(indexPath.section == 0){
            goodsList = self.currenFlashSale.goods;
        }else{
            EJSRecommendModel *model = self.recommendCategoryList[indexPath.section - 1];
            goodsList = model.list;
        }
    }
    else{
        EJSRecommendModel *model = self.recommendCategoryList[indexPath.section];
        goodsList = model.list;
    }
    [horizontalGoodsCell setGoodsList:goodsList];
    return horizontalGoodsCell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        if(_currenFlashSale && indexPath.section == 0){
            EJSFlashSaleHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSFlashSaleHeaderReusableView" forIndexPath:indexPath];
            if([self flashSaleUnderway]){
                [self flashSaleTimerCountDown];
                headerView.statusLabel.text = @"抢购中";
            }else{
                headerView.timeCover.hidden = YES;
                headerView.statusLabel.text = [NSString stringWithFormat:@"下一场抢购 %@ 开始", self.currenFlashSale.startTime];
            }
            return headerView;
        }else{
            EJSHomeRecommendHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSHomeRecommendHeaderReusableView" forIndexPath:indexPath];
            EJSRecommendModel *model;
            if(self.flashSaleList.count > 0 ){
                model = self.recommendCategoryList[indexPath.section - 1];
            }else{
                model = self.recommendCategoryList[indexPath.section];
            }
            [headerView.imageView setImageWithUrl:model.recommendPic];
            [headerView whenTapped:^{
                EJSCategoryModel *categoryModel = [EJSCategoryModel new];
                categoryModel.categoryId = model.categoryId;
                categoryModel.categoryName = model.categoryName;
                EJSGoodsListViewController *goodsListVC = [[EJSGoodsListViewController alloc] initWithNibName:@"EJSGoodsListViewController" bundle:nil];
                goodsListVC.categoryModel = categoryModel;
                [self.navigationController pushViewController:goodsListVC animated:YES];
            }];
            return headerView;
        }
    }else{
        EJSFlashSaleFooterReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSFlashSaleFooterReusableView" forIndexPath:indexPath];
        [footerView.nextButton addTarget:self action:@selector(nextFlashSaleAction) forControlEvents:UIControlEventTouchUpInside];
        return footerView;
    }
}

- (void)nextFlashSaleAction{
    if(self.flashSaleList.count > 0){
        NSInteger index = [self.flashSaleList indexOfObject:_currenFlashSale];
        if(index + 1 < self.flashSaleList.count){
            self.currenFlashSale = self.flashSaleList[index + 1];
            [self.collectionView reloadData];
        }else{
           [[HUDHelper sharedInstance] tipMessage:@"暂无下一场抢购"];
        }
    }else{
        [[HUDHelper sharedInstance] tipMessage:@"暂无下一场抢购"];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 0, 15, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *goodsList = nil;
    if(_currenFlashSale){
        if(indexPath.section == 0){
            goodsList = self.currenFlashSale.goods;
        }else{
            EJSRecommendModel *model = self.recommendCategoryList[indexPath.section - 1];
            goodsList = model.list;
        }
    }
    else{
        EJSRecommendModel *model = self.recommendCategoryList[indexPath.section];
        goodsList = model.list;
    }
    if(goodsList.count > 0){
        return CGSizeMake(ScreenWidth, 166);
    }
    return CGSizeMake(ScreenWidth, 5);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if(self.flashSaleList.count > 0 && section == 0){
        return CGSizeMake(ScreenWidth, 89);
    }
    return CGSizeMake(ScreenWidth, EJSHomeRecommendHeaderReusableViewHeight);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if(self.flashSaleList.count > 0 && section == 0){
        return CGSizeMake(ScreenWidth, 76);
    }
    return CGSizeZero;
}

#pragma mark - Request
- (void)getRecommendAdRequest{
    FlyWeakSelf
    EJSAdRequest *req = [EJSAdRequest new];
    req.type = @"index";
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.recommendAdList = response.data;
    } failHandler:^(BaseResponse *response) {
        
    }];
}

- (void)getRecommendCategoryList{
    FlyWeakSelf
    [[EJSRecommendRequest new] asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.recommendCategoryList = response.data;
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}

- (void)getFlashSaleList{
    FlyWeakSelf
    [[EJSFlashSaleRequest new] asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.flashSaleList = [NSMutableArray arrayWithArray:response.data];
        if(weakSelf.flashSaleList.count > 0){
            weakSelf.currenFlashSale = weakSelf.flashSaleList.firstObject;
        }
    } failHandler:^(BaseResponse *response) {
        
    }];
}

@end
